package handler

import (
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/hashicorp/consul/api"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_config/model"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_config/repository"
	"github.com/spf13/viper"
)

// 注册服务，单个服务注册
func ServiceRegisterSingle(index int, serviceData model.FuncServiceRegister) bool {

	DB := repository.GetDB()

	lowerType := strings.ToLower(serviceData.ExporterType)
	serviceID := serviceData.IP + "-" + lowerType + "_exporter"
	var serviceState bool = false
	var c *repository.ConsulApi

	consulNum := viper.GetInt("consul_num." + serviceData.Datacenter)

	// 检查集群中是否已经注册，则将变量c赋为已经注册的consul客户端
	for i := 1; i <= consulNum; i++ {
		urlCheck := viper.GetString("consul." + serviceData.Datacenter + ".consul-" + strconv.Itoa(i))
		cCheck := repository.CreateConsulClient(urlCheck + ":8085")
		state := cCheck.CheckService(serviceID)
		if state {
			log.Printf("INFO: Service %v is registered in consul-%v", serviceID, i)
			serviceState = true
			c = cCheck
			break
		}
	}

	// 如果没有注册，则将变量c循环赋consul客户端
	if !serviceState {
		count := index%consulNum + 1
		url := viper.GetString("consul." + serviceData.Datacenter + ".consul-" + strconv.Itoa(count))
		c = repository.CreateConsulClient(url + ":8085")
	}

	// 创建服务实例
	service := api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    lowerType + "_exporter",
		Address: serviceData.IP,
		Kind:    api.ServiceKind(lowerType),
		Port:    viper.GetInt("exporter_port." + lowerType + "_exporter"),
		Tags:    []string{"prometheus-" + serviceData.MinIndex, lowerType + "_exporter", serviceData.Datacenter},
		Meta: map[string]string{
			"hostname":     serviceData.Hostname,
			"short_name":   serviceData.ShortName,
			"service_name": serviceData.ServiceName,
			"app_team":     serviceData.AppTeam,
			"system_id":    serviceData.SystemID,
		},
		Check: &api.AgentServiceCheck{
			TCP:      serviceData.IP + ":" + viper.GetString("exporter_port."+lowerType+"_exporter"),
			Interval: "45s",
			Timeout:  "3s",
		},
	}

	log.Printf("INFO: Begin register")
	// 注册服务
	serviceState = c.RegisterService(service)
	// 检查是否注册成功，并更新数据库
	if serviceState {
		DB.Table("cmdb_all_servers").Where("hostname = ? AND ip = ?", serviceData.Hostname, serviceData.IP).
			Update(lowerType+"_exporter", "registered")
		log.Printf("%v register success", serviceID)
	} else {
		log.Printf("%v register failed", serviceID)
	}
	time.Sleep(500 * time.Millisecond)
	return serviceState
}
